package com.emm.yixun.website.controller.estate;

//框架包
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.BaseCodeType;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectImg;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeTypeDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectImgDto;
import com.emm.yixun.common.model.dto.ProjectInfoDto;
import com.emm.yixun.common.model.dto.ProjectProcdefDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.enums.CodeTypeEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.estate.service.ProjectImgServiceFacade;
import com.emm.yixun.estate.service.ProjectProcdefServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.SalesGroupUserServiceFacade;
import com.emm.yixun.system.service.BaseCodeTypeServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.estate.ProjectInfoVo;
import com.emm.yixun.website.vo.estate.ProjectSettingVo;
import com.emm.yixun.website.vo.estate.ProjectVo;
//变化的引用
//common
//website

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

@Controller
@RequestMapping("/estate/projectBasic/")
public class ProjectBasicController extends BaseController<Project> {

	@Autowired
	private ProjectServiceFacade projectServiceFacade;



	@Autowired
	private ProjectImgServiceFacade projectImgServiceFacade;

	@Autowired
	private UserServiceFacade userServiceFacade;


	@Autowired
	private SalesGroupUserServiceFacade salesGroupUserServiceFacade;

	@Autowired
	private ProjectProcdefServiceFacade projectProcdefServiceFacade;

	@Autowired
	private RepositoryService repositoryService;
	
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	
	@Autowired
	private BaseCodeTypeServiceFacade baseCodeTypeServiceFacade;

	@Autowired
	private MerchantServiceFacade merchantServiceFacade;


	/**
	 * 方法描述 : M2基础版本项目保存方法
	 */

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(ProjectVo projectVo, ProjectInfoVo projectInfoVo,
					   ProjectSettingVo projectSettingVo, Long projectInfoId,
					   Long settingId, Long imgId, String otherProjectType) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		//总经理
		if (null == projectSettingVo.getGeneralManager()) {
			projectSettingVo.setGeneralManager(null);
		}
		// 项目总
		if (null == projectSettingVo.getProjectLeader()) {
			projectSettingVo.setProjectLeader(null);
		}
		//经济总
		if (null ==projectSettingVo.getSaleLeader()) {
			projectSettingVo.setSaleLeader(null);
		}

		//销售经理
		if (null ==projectSettingVo.getFieldLeader()) {
			projectSettingVo.setFieldLeader(null);
		}

		// 财务经理
		if (null == projectSettingVo.getFinanceLeader()) {
			projectSettingVo.setFinanceLeader(null);
		}
		//销管经理
		if (null == projectSettingVo.getMaLeader()) {
			projectSettingVo.setMaLeader(null);
		}
		// 区域领导
		if (null == projectSettingVo.getAreaLeader()) {
			projectSettingVo.setAreaLeader(null);
		}
		// 区域经理
		if (null == projectSettingVo.getAreaManager()) {
			projectSettingVo.setAreaManager(null);
		}
		/*String authStr = "estate:project:add";
		if(null != projectInfoId){
			authStr = "estate:project:edit";
		}*/
		if (true/*ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, authStr))*/) {
			try {
				projectInfoVo.setId(projectInfoId);
				projectSettingVo.setId(settingId);
				User user = ShiroUtil.getCurrentUser();
				if (StringUtils.isNotBlank(otherProjectType)) {
					// 将其它产品类型存到remark字段中，避免新加字段
					projectVo.setRemark(otherProjectType);
				}
				projectVo.setMerchantId(user.getMerchantId());
				projectVo.setUserCode(user.getUserCode());
				projectVo.setCreateUserId(user.getId());
				projectVo.setDelFlag("0");
				projectVo.setUpdateUserId(user.getId());
				projectVo.setUpdateTime(new Date());

				projectInfoVo.setMerchantId(user.getMerchantId());
				projectInfoVo.setUserCode(user.getUserCode());
				projectInfoVo.setCreateUserId(user.getId());
				projectInfoVo.setDelFlag("0");
				projectInfoVo.setUpdateUserId(user.getId());
				projectInfoVo.setUpdateTime(new Date());

				projectSettingVo.setMerchantId(user.getMerchantId());
				projectSettingVo.setUserCode(user.getUserCode());
				projectSettingVo.setCreateUserId(user.getId());
				projectSettingVo.setDelFlag("0");
				projectSettingVo.setUpdateUserId(user.getId());
				projectSettingVo.setUpdateTime(new Date());

				Validator validator = new Validator();
				List<ConstraintViolation> projectVoError = validator
						.validate(projectVo);
				List<ConstraintViolation> projectInfoVoError = validator
						.validate(projectInfoVo);
				List<ConstraintViolation> projectSettingError = validator
						.validate(projectSettingVo);
				if (projectVoError != null && projectVoError.size() > 0) {
					ar.setFailMsg(projectVoError.get(0).getMessage());
					return ar;
				}
				if (projectInfoVoError != null && projectInfoVoError.size() > 0) {
					ar.setFailMsg(projectInfoVoError.get(0).getMessage());
					return ar;
				}
				if (projectSettingError != null
						&& projectSettingError.size() > 0) {
					ar.setFailMsg(projectSettingError.get(0).getMessage());
					return ar;
				}

				ProjectDto projectDto = BeanUtil.convert2T(new ProjectDto(),
						projectVo);
				ProjectInfoDto projectInfoDto = BeanUtil.convert2T(
						new ProjectInfoDto(), projectInfoVo);
				ProjectSettingDto projectSettingDto = BeanUtil.convert2T(
						new ProjectSettingDto(), projectSettingVo);
				// 保存项目信息
				Response<ProjectDto> response = projectServiceFacade.save(projectDto, projectInfoDto, projectSettingDto,null);
				if (!response.isSuccess()) {
					ar.setFailMsg(response.getResultMessage());
					return ar;
				}
				// 保存图片
				saveProjectImg(user, response.getEntity(), projectVo);

				// 新增销售组
				projectSettingDto.setProjectCode(response.getEntity()
						.getProjectCode());
				projectSettingDto.setProjectId(response.getEntity().getId());
				initSalesGroup(user, projectSettingDto);
				// 初始化流程
				if (null == projectVo.getId()) {
					// 项目新增初始化审批流程(ym)
					initProcessDef(response.getEntity().getId(), response
							.getEntity().getProjectCode(), user);
					
					// 初始化业务参数
					initBaseCodeValue(response.getEntity());
				}

				ar.setSucceedMsg(projectVo.getId() == null ? Const.SAVE_SUCCEED
						: Const.UPDATE_SUCCEED);
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(e.getMessage());
			}
		}
		return ar;
	}
	
	public void initBaseCodeValue(ProjectDto dto) {

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		// if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:baseCodeValue:init"))){
		try {
			User user = ShiroUtil.getCurrentUser();
			BaseCodeTypeDto bctDto = new BaseCodeTypeDto();
			bctDto.setRemark("初始化");
			bctDto.setMerchantId(dto.getMerchantId());
			bctDto.setProjectId(dto.getId());
			bctDto.setDelFlag("0");
			ResponseList<BaseCodeType> bctRes = baseCodeTypeServiceFacade.findByDto(bctDto);
			boolean isInit = false;
			if (bctRes.isSuccess()) {
				List<BaseCodeType> bctList = bctRes.getEntity();
				if (null != bctList && bctList.size() > 0) {
					isInit = true;
				}
			}
			String[] codeTypeArr = { "获知途径", "客户性质", "置业动机", "关注重点", "需求楼层", "生活服务", "生活配套", "希望庭院具备功能", "家庭结构",
					"目前居住的物业类型", "首次接触方式", "证件类型", "车驾品牌", "乐于参加的活动类型", "兴趣爱好", "日常信息获知途径", "目前居住的户型结构", 
					"学历","从事行业","公司性质","联系方式","目前居住/办公的房子属性"};
			String[] codeTypeArr2 = { "informedWay", "customerNature", "theirMotives", "focus", "floor", "lifeService", "lifeSupport", "courtyardFunction", "familyJie",
					"currentlyProperty", "contactWay", "documentType", "frameBrand", "activityType", "hobby", "richangxinxi", "currentlyStructure", 
					"academicQualifications","congshihangye","companyXingzhi","contactInformation","currentlyHouse"};
			String[][] codeValueArrs = {
					{ "报广媒体", "网络", "电台广播", "户外广告", "楼宇广告", "杂志", "直投", "会员", "展厅推荐", "房交会", "朋友介绍", "全员营销", "外部推荐",
							"CALL客", "短信", "派单", "工地现场及围挡", "拓客", "中介" },
					{ "自然到访", "员工", "工抵", "全员营销", "外部推荐", "渠道客户", "老带新", "分销推荐" },
					{ "婚房", "改善", "投资", "自住", "养老", "度假" },
					{ "地理位置", "商业配套", "周边配套", "生态环境", "健康服务", "建筑风水", "户型设计", "教育机构" },
					{ "多层", "小高层", "高层", "1层", "2层", "3层", "4层", "5层", "6层" },
					{ "酒店式礼宾服务", "酒店式前台服务", "酒店式商务服务", "菜单式房屋清洁服务", "私人生活秘书", "送餐服务", "文化、体育活动", "专车接送服务", "房屋租赁管理服务",
							"电话及访客留言", "健康、教育课程服务", "24小时便利店", "银行", "医院", "学校", "地铁", "公交", "菜场", "超市", "健身房", "药店",
							"图书馆" },
					{ "银行", "医院", "学校", "地铁", "公交", "菜场", "超市", "健身房" },
					{ "游泳池", "SPA池", "水景池", "烧烤台", "凉亭" },
					{ "独居", "夫妻二人", "二代同堂", "三代同堂", "四代同堂" },
					{ "酒店式公寓", "高层公寓", "多层公寓", "平层官邸", "排屋", "别墅", "中式大宅" },
					{ "来电", "来访" },
					{ "身份证", "护照", "营业执照", "户口薄", "军官证", "临时身份证", "港澳台同胞来往通行证", "边民出入境通行证", "外国人永久居留证", "警官证", "士兵证" },
					{ "无车", "奔驰", "宝马", "保时捷", "雷克萨斯", "丰田", "本田", "大众", "雪佛兰", "英菲尼迪", "奥迪", "沃尔沃", "标致", "现代", "别克",
							"福特", "马自达" },
					{ "修身养生类", "知识学习类", "少儿教育类", "老年人关爱类", "互动交流类", "园区体验类", "奢侈品体验类" },
					{ "运动", "上网", "收藏", "音乐", "文学", "摄影", "棋牌", "舞蹈", "旅游", "字画", "阅读", "影视剧", "综艺娱乐", "汽车", "奢侈品",
							"科技", "金融理财", "美容", "养生", "茶艺", "宠物", "烹饪" },
					{ "报纸", "网络", "电台广播", "微信等社交软件", "电视", "短信", "DM单页", "朋友" },
					{ "一室一厅", "两室一厅", "三室一厅", "三室两厅", "两室两厅" },
					{ "大专", "本科", "硕士", "博士", "博士后" },
					{ "工业制造", "贸易", "农林牧渔", "采矿业", "建筑业","房地产业","金融业","交通运输仓储和邮政业","IT行业（信息传输、计算机服务和软件业）","酒店/餐饮业","租赁（和商务服务业）","教育","医疗卫生","文化和体育","旅游","公共管理（政府机关等）和社会组织","科学研究和技术服务","国际组织" },
					{ "私企", "央企", "国企", "混合所有制"},
					{ "电话", "短信", "邮件"},
					{ "安置房", "自建房", "租房","单位分房","07年前老商品房","07年后老商品房","近百年来房子"}
					
				};

			if (!isInit) {
				baseCodeValueServiceFacade.baseCodeValueInit(user, dto, codeTypeArr, codeTypeArr2, codeValueArrs,
						CodeTypeEnum.CUSTOMER.getNo());
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
	}

	private void initProcessDef(Long projectId, String projectCode, User user) {
		try {
			//商户自定义流程前缀
			String procDefinedPrefix = getProcDefinedPrefix(user);
			for (ProcessTypeEnums pte : ProcessTypeEnums.values()) {
				ProcessDefinitionQuery query = repositoryService
						.createProcessDefinitionQuery();
				
				//查询流程,获取前缀信息
				String pteNo = pte.getNo();
				String pteInit = pte.getInit();
				//petInit=1为定制化流程
				if(!"0".equals(pteInit)){
					continue;
				}
				//新的流程类型
				String newPteKey = "";
				//新流程类型对应的流程key
				//由于流程Key可能与原定义key不一致(主要原因为定义的字段太长了,不得不改),名字给修改过.
				//需重新获取一遍.
				String newPteNo = pteNo;
				if(StringUtils.isNotEmpty(procDefinedPrefix)){
					newPteKey = procDefinedPrefix + pteNo;
					ProcessTypeEnums ptEnums = ProcessTypeEnums.getByNo(newPteKey);
					if(null == ptEnums){
						continue;
					}
					newPteNo = ptEnums.getDes();
				}
				
				List<ProcessDefinition> processDefinitionList = query
						.processDefinitionKey(newPteNo).list();
				if (null == processDefinitionList
						|| processDefinitionList.size() == 0) {
					continue;
				}
				ProjectProcdefDto ppd = new ProjectProcdefDto();
				ppd.setMerchantId(user.getMerchantId());
				ppd.setUserCode(user.getUserCode());
				ppd.setProjectId(projectId);
				ppd.setAccessCode(projectCode);
				ppd.setCreateUserId(user.getId());
				ppd.setUpdateTime(new Date());
				ppd.setDelFlag("0");
				ProcessDefinition processDefinition = processDefinitionList
						.get(0);
				ppd.setProcKey(processDefinition.getKey());
				ppd.setProcdefId(processDefinition.getId());
				ppd.setProcName(processDefinition.getName());
				ppd.setProcType(pte.getNo());
				projectProcdefServiceFacade.save(ppd);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}

	}

	private void initSalesGroup(User user, ProjectSettingDto projectSettingDto)
			throws Exception {
		// 组装销售组
		SalesGroupDto dto = new SalesGroupDto();
		dto.setProjectId(projectSettingDto.getProjectId());
		dto.setProjectCode(projectSettingDto.getProjectCode());
		dto.setName("管理组");
		dto.setSort(0);
		dto.setStatus("0");
		dto.setSaleAttr("1");
		dto.setRemark("新建项目,初始化管理组");
		dto.setOriginal("project");
		// 组装销售组成员
		List<SalesGroupUserDto> userDto = new ArrayList<SalesGroupUserDto>();
		// 公司总经理
		SalesGroupUserDto sgu0 = new SalesGroupUserDto();
		sgu0.setUserId(projectSettingDto.getGeneralManager());
		sgu0.setStatus("0");
		sgu0.setRemark("新建项目,初始化管理组公司总经理");
		// 项目负责人
		SalesGroupUserDto sgu1 = new SalesGroupUserDto();
		sgu1.setUserId(projectSettingDto.getProjectLeader());
		sgu1.setStatus("0");
		sgu1.setRemark("新建项目,初始化管理组项目负责人");
		// 营销负责人
		SalesGroupUserDto sgu2 = new SalesGroupUserDto();
		sgu2.setUserId(projectSettingDto.getSaleLeader());
		sgu2.setStatus("0");
		sgu2.setRemark("新建项目,初始化管理组营销负责人");

		// 案场负责人
		SalesGroupUserDto sgu3 = new SalesGroupUserDto();
		sgu3.setUserId(projectSettingDto.getFieldLeader());
		sgu3.setStatus("0");
		sgu3.setRemark("新建项目,初始化管理组案场负责人");

		// 财务负责人
		SalesGroupUserDto sgu4 = new SalesGroupUserDto();
		sgu4.setUserId(projectSettingDto.getFinanceLeader());
		sgu4.setStatus("0");
		sgu4.setRemark("新建项目,初始化管理组财务负责人");
		// 销管负责人
		SalesGroupUserDto sgu5 = new SalesGroupUserDto();
		sgu5.setUserId(projectSettingDto.getMaLeader());
		sgu5.setStatus("0");
		sgu5.setRemark("新建项目,初始化管理组销管负责人");
		// 区域负责人
		SalesGroupUserDto sgu6 = new SalesGroupUserDto();
		sgu6.setUserId(projectSettingDto.getAreaLeader());
		sgu6.setStatus("0");
		sgu6.setRemark("新建项目,初始化管理组区域负责人");
		if (isAdd(userDto, sgu0))
			userDto.add(sgu0);
		if (isAdd(userDto, sgu1))
			userDto.add(sgu1);
		if (isAdd(userDto, sgu2))
			userDto.add(sgu2);
		if (isAdd(userDto, sgu3))
			userDto.add(sgu3);
		if (isAdd(userDto, sgu4))
			userDto.add(sgu4);
		if (isAdd(userDto, sgu5))
			userDto.add(sgu5);
		if (isAdd(userDto, sgu6))
			userDto.add(sgu6);
		Response<Integer> response = salesGroupUserServiceFacade
				.batchGroupUser(user, dto, userDto);
		if (!response.isSuccess()) {
			throw new RuntimeException(response.getResultMessage());
		}

	}

	private boolean isAdd(List<SalesGroupUserDto> userDto,
						  SalesGroupUserDto salesGroupUserDto) {
		if(salesGroupUserDto.getUserId()==null)return false;
		for (SalesGroupUserDto sgud : userDto) {
			if (sgud.getUserId().compareTo(salesGroupUserDto.getUserId()) == 0) {
				return false;
			}
		}
		return true;
	}

	private void saveProjectImg(User user, ProjectDto projectDto,
								ProjectVo projectVo) {
		if (null == projectDto)
			return;
		if (null == projectVo)
			return;
		// 删除这个项目下面所有的图片
		if (projectDto.getId() != null) {
			ProjectImgDto dto = new ProjectImgDto();
			dto.setProjectId(projectDto.getId());
			dto.setProjectImgCode("projectCode");
			ResponseList<ProjectImg> list = projectImgServiceFacade
					.findByDto(dto);
			if (list.isSuccess() && list.getEntity() != null) {
				for (ProjectImg img : list.getEntity()) {
					projectImgServiceFacade.deleteByPrimaryKey(img.getId());
				}
			}
		}
		Long projectId = projectDto.getId();
		String projectCode = projectDto.getProjectCode();
		// 项目logo
		saveImg(user, projectId, projectCode, projectVo.getLogoUrl(), "1");
		// 总平面图
		saveImg(user, projectId, projectCode, projectVo.getPlaneUrl(), "2");
		// 周边配套图
		saveImg(user, projectId, projectCode, projectVo.getPeripheryUrl(), "3");
		// 交通图
		saveImg(user, projectId, projectCode, projectVo.getTrafficUrl(), "4");
		// 实景图
		saveImg(user, projectId, projectCode, projectVo.getRealUrl(), "5");
		// 样板图
		saveImg(user, projectId, projectCode, projectVo.getModelUrl(), "6");
		// 效果图
		saveImg(user, projectId, projectCode, projectVo.getEffectUrl(), "7");
	}

	private void saveImg(User user, Long projectId, String projectCode,
						 String imgUrl, String type) {
		if (StringUtils.isBlank(imgUrl))
			return;
		String[] urls = imgUrl.split(";");
		if (null == urls || urls.length <= 0)
			return;
		for (int i = 0; i < urls.length; i++) {
			ProjectImgDto projectImgDto = new ProjectImgDto();
			projectImgDto.setUserCode(user.getUserCode());
			projectImgDto.setMerchantId(user.getMerchantId());
			projectImgDto.setDelFlag("0");
			projectImgDto.setAccessCode(projectCode);
			projectImgDto.setLargeUrl(urls[i]);
			projectImgDto.setNormalUrl(urls[i]);
			projectImgDto.setSmallUrl(urls[i]);
			projectImgDto.setProjectImgType(type);
			projectImgDto.setProjectCode(projectCode);
			projectImgDto.setAccessCode(projectCode);
			projectImgDto.setProjectId(projectId);
			projectImgDto.setCreateUserId(user.getId());
			projectImgDto.setProjectImgCode("projectCode");
			projectImgServiceFacade.save(projectImgDto);
		}

	}

	/**
	 * 获取流程自定义前缀
	 * @param user
	 * @return
	 */
	public String getProcDefinedPrefix(User user){
		String result = "";
		Response<Merchant> merchantResponse = merchantServiceFacade.findById(user.getMerchantId());
		if(merchantResponse.isSuccess()&&merchantResponse.getEntity()!=null){
			String information = merchantResponse.getEntity().getPhoneInformation();
			com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(information);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
			    String type = jsonObject.getString("type");
			    String status = jsonObject.getString("status");
			    if("99".equals(type) && StringUtils.isNotEmpty(status)){
			    	result = status;
			    }
			}
		}
		return result;
    }
	
	private User getUserById(Long id) {
		if (null != id) {
			Response<User> response = userServiceFacade.findById(id);
			if (response.isSuccess()) {
				return response.getEntity();
			}
		}
		return new User();
	}


}
